import {Utils} from "jboot-env";

let buttonIsLoaded = false;

export default function (http, store) {
	const AUTH_REQUEST = {
		GET_INFO: 'info',
		GET_MENU: 'menus',
		GET_BUTTON: 'buttons'
	}

	const authRequest = authMethod => http.api('auth', authMethod);

	return {
		loadUser: async () => {
			const {user} = store.getters;

			if(Utils.isNotEmpty(user)) return user;

			return authRequest(AUTH_REQUEST.GET_INFO).then(response => {
				const responseUser = response.data || {};

				store.commit('SAVE_USER', responseUser);

				return responseUser;
			});
		},

		loadMenus: async () => {
			return authRequest(AUTH_REQUEST.GET_MENU).then(response => {
				const menus = response.data;

				store.commit('SAVE_MENUS', menus);

				return menus;
			});
		},

		loadButtons: async () => {
			let {buttons} = store.getters;

			if(buttonIsLoaded === false && Utils.isEmpty(buttons)){
				return authRequest(AUTH_REQUEST.GET_BUTTON).then(response => {
					store.commit('SAVE_BUTTONS', buttons = Utils.blank2Default(response.data, []).map(item => item.code));

					buttonIsLoaded = true;

					return buttons;
				});
			}

			return buttons;
		}
	};
};
